const Koa = require("koa");
const router = require("koa-router")();
const session = require("koa-session");
const views = require("koa-views");
const parser = require("koa-parser");
const nunjuck = require("nunjucks")
const app = new Koa();


app.keys = ["110713"];

// 渲染模板
app.use(views(__dirname + "/views", {
    map: { html: "nunjucks" }
}))

//引入session模块  并且设置过期时间为3600秒
app.use(session({
    maxAge: 3600 * 1000  
}, app));

app.use(parser());


app.use(router.routes());

//首页
router.get("/", async (ctx, next) => {
    await ctx.render("home.html")
})

//登录
router.get("/login", async (ctx, next) => {
    
    if(ctx.session.user){
        await ctx.redirect("/")
    }else{
        await ctx.render("login.html")
    }
})

//处理请求的路由
router.post("/login", async (ctx, next) => {

    let username = ctx.request.body.username;
    let password = ctx.request.body.password;
    if (username == "milu" && password == "123456") {
        ctx.session.user = username;
            ctx.redirect("/book")      
    } else {
        ctx.redirect("/")
    }
})

//书籍界面
router.get("/book", async (ctx, next) => {
    if (ctx.session.user) {
        let root = ctx.session.user ;
        await ctx.render("book.html",{
            root : root
        });
    }
    else{
        ctx.redirect("/");
    }
})


//视频界面
router.get("/video", async (ctx, next) => {

    if(ctx.session.user){
        let videoes = ["送你的一朵小红花", "少年的你"];
    await ctx.render("video.html", {
        videoes
    })
    }
    else{
        ctx.redirect("/")
    }
    
})

//注销
router.get("/logout",async(ctx,next)=>{
    ctx.session.user ="";
    ctx.redirect("/");
})

app.listen(3000, () => {
    console.log("服务器运行的地址是:http:127.0.0.1:3000");
})